package com.pdd.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pdd.mall.dto.ReviewParam;
import com.pdd.mall.entity.Order;
import com.pdd.mall.entity.OrderItem;
import com.pdd.mall.entity.Product;
import com.pdd.mall.entity.Review;
import com.pdd.mall.mapper.OrderItemMapper;
import com.pdd.mall.mapper.OrderMapper;
import com.pdd.mall.mapper.ProductMapper;
import com.pdd.mall.mapper.ReviewMapper;
import com.pdd.mall.service.ReviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 评价服务实现类
 */
@Service
public class ReviewServiceImpl implements ReviewService {

    @Autowired
    private ReviewMapper reviewMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    @Transactional
    public Review addReview(ReviewParam param, Long userId) {
        // 1. 验证订单是否存在且属于当前用户
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_no", param.getOrderNo());
        orderQueryWrapper.eq("user_id", userId);
        orderQueryWrapper.eq("status", 3); // 已完成状态
        Order order = orderMapper.selectOne(orderQueryWrapper);

        if (order == null) {
            throw new IllegalArgumentException("订单不存在或状态不正确");
        }

        // 2. 验证商品是否在订单中
        QueryWrapper<OrderItem> orderItemQueryWrapper = new QueryWrapper<>();
        orderItemQueryWrapper.eq("order_id", order.getId());
        orderItemQueryWrapper.eq("product_id", param.getProductId());
        OrderItem orderItem = orderItemMapper.selectOne(orderItemQueryWrapper);

        if (orderItem == null) {
            throw new IllegalArgumentException("商品不在订单中");
        }

        // 3. 检查是否已评价
        if (isOrderReviewed(param.getOrderNo(), param.getProductId())) {
            throw new IllegalArgumentException("该商品已评价");
        }

        // 4. 获取商品信息
        Product product = productMapper.selectById(param.getProductId());
        if (product == null) {
            throw new IllegalArgumentException("商品不存在");
        }

        // 5. 创建评价
        Review review = new Review();
        review.setUserId(userId);
        review.setOrderId(order.getId());
        review.setOrderNo(param.getOrderNo());
        review.setProductId(param.getProductId());
        review.setProductName(product.getName());
        review.setRating(param.getRating());
        review.setContent(param.getContent());
        review.setAnonymous(param.getAnonymous());

        // 处理图片
        if (param.getImages() != null && !param.getImages().isEmpty()) {
            try {
                review.setImages(objectMapper.writeValueAsString(param.getImages()));
            } catch (JsonProcessingException e) {
                throw new RuntimeException("处理评价图片失败", e);
            }
        }

        // 6. 保存评价
        reviewMapper.insert(review);

        return review;
    }

    @Override
    public Page<Review> getProductReviews(Long productId, Integer pageNum, Integer pageSize) {
        Page<Review> page = new Page<>(pageNum, pageSize);

        QueryWrapper<Review> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        queryWrapper.orderByDesc("create_time");

        return reviewMapper.selectPage(page, queryWrapper);
    }

    @Override
    public Page<Review> getUserReviews(Long userId, Integer pageNum, Integer pageSize) {
        Page<Review> page = new Page<>(pageNum, pageSize);

        QueryWrapper<Review> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("create_time");

        return reviewMapper.selectPage(page, queryWrapper);
    }

    @Override
    public boolean isOrderReviewed(String orderNo, Long productId) {
        QueryWrapper<Review> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        queryWrapper.eq("product_id", productId);

        return reviewMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public Review getOrderReview(String orderNo, Long productId) {
        QueryWrapper<Review> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        queryWrapper.eq("product_id", productId);

        return reviewMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean deleteReview(Long id, Long userId) {
        QueryWrapper<Review> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.eq("user_id", userId);

        return reviewMapper.delete(queryWrapper) > 0;
    }
}
